import { Component, OnInit,ChangeDetectorRef } from "@angular/core";
import { Router } from "@angular/router";
import { HttpService } from '../../../services/http.service';
import { ModalController, ActionSheetController } from '@ionic/angular';
import { WebsocketService } from '../../../services/websocket.service';
import { LoginInfoService } from '../../../services/login-info.service';
import { PopoverComponent } from '../../components/popover/popover.component';
import { UpphotoService } from '../../../services/upphoto.service';
import { commService } from '../../../services/comm.service'
import { DomSanitizer } from '@angular/platform-browser';
import { BaseUiService } from '../../../services/base-ui.service';
@Component({
  selector: "app-startVideo",
  templateUrl: "./startVideo.page.html",
  styleUrls: ["./startVideo.page.scss"]
})
export class StartVideoPage implements OnInit {
  slideOpts = {
    effect: "flip", //轮播效果
    autoplay: {
      delay: 4000
    },
    loop: false
  };

  // roomId= JSON.parse(window.localStorage.getItem("orderInfo")).roomId||'4b6b7747-7e01-48b7-a799-c7a5b1511eee'
  
  roomId= this.LoginInfoService.getlocal('orderInfo').roomId ||'4b6b7747-7e01-48b7-a799-c7a5b1511eee'
  public tabIndex = '0';
  materialContent = [];
  imgList = []//保存材料照片
  commissionContent;//草拟文书内容
  xwblContent;////草拟文书内容
  jftzContent = {
    address: "",//发证地点
    gzf: "",//公证费用
    sxf: "",//摄像费用
    qtf: "",//其他费用
    smf: '',//上门服务费
    flf: "",//法律服务费
    replayFlag: false
  };
  public shenForm = [];
  public daiLiForm = {};
  public qiYeForm = [];
  public baseForm = {};
  public imglist = [];//传入的图片
  public signatureImg: any //签字的码值
  public signatureId: any //服务器返回的图片地址
  public isShowimg: boolean = false;
  constructor(
    public baseUiService:BaseUiService,
    public commService: commService,
    public router: Router,
    public HttpService: HttpService,
    public LoginInfoService: LoginInfoService,
    public modalController: ModalController,
    public upphotoService: UpphotoService,
    public actionSheetController: ActionSheetController,
    public wsCoket: WebsocketService,
    public sanitizer: DomSanitizer,
    private cd: ChangeDetectorRef,
  ) {
  }

  jsonArry(data) {
    let arr = []
    data.info.forEach(e => {
      let obj = {
        annexFileList: '',
        imgPathList: e
      }
      arr.push(obj)
    })
    return arr
  }

  ngOnInit() {
    var that = this;
    try{
      this.commService.initRoom(this.roomId,"123213213213");
    }catch(e){
          console.log("123")
    }
    let userInfo = this.LoginInfoService.getlocal("user")
    
    this.wsCoket.getMessage().subscribe(data => {
      if (data.code == '023') {
        this.tabIndex = "4";
        this.jftzContent.address = data.info;
      } else if (data.code == '025') {
        this.tabIndex = "4";
        this.jftzContent.gzf = data.info;
      } else if (data.code == '026') {
        this.tabIndex = "4";
        this.jftzContent.flf = data.info;
      } else if (data.code == '027') {
        this.tabIndex = "4";
        this.jftzContent.smf = data.info;
      } else if (data.code == '028') {
        this.tabIndex = "4";
        this.jftzContent.sxf = data.info;
      } else if (data.code == '029') {
        this.tabIndex = "4";
        this.jftzContent.qtf = data.info;
      } else if (data.code == '00') {//申请人
        this.shenForm = data.info
      } else if (data.code == '01') {//代理
        this.daiLiForm = data.info
      } else if (data.code == '02') {//企业单位
        this.qiYeForm = data.info
      } else if (data.code == '001') {//公证内容
        this.baseForm = data.info
      } else if (data.code == '101') {
        this.imglist = this.jsonArry(data)//数据整理
        setTimeout(()=>{
          that.isShowimg = true
        },200)
      } else if (data.code == '102') {
        this.isShowimg = false;
        this.iconclick();
        this.presentPopover()
        this.tabIndex = '1'
      } else if (data.code == '104') {//告知书查看
        this.imglist = this.jsonArry(data)//数据整理
        setTimeout(()=>{
          that.isShowimg = true
        },200)
      } else if (data.code == '110') {//告知书查看
        this.imglist = this.jsonArry(data)//数据整理
        setTimeout(()=>{
          that.isShowimg = true
        },200)
      } else if (data.code == "502") {//缴费通知
        this.tabIndex = "4";
      } else if (data.code == '510') {
        this.tabIndex = "2";
        this.commissionContent = this.sanitizer.bypassSecurityTrustHtml(data.info);
      } else if (data.code == '511') {
        this.tabIndex = "3";
        this.xwblContent = this.sanitizer.bypassSecurityTrustHtml(data.info);
      } else if (data.code == '40002') {
        this.materialContent.splice(data.index, 1);
      } else if (data.code == '106') {
        this.imglist = this.jsonArry(data)//数据整理
        setTimeout(()=>{
          that.isShowimg = true
        },200)
      } else if (data.code == '105') {
        this.isShowimg = false;
        this.iconclick();
        this.presentPopover()
        this.tabIndex = "4";
      } else if (data.code == "300") {//付款
        this.isShowimg = false;
        this.iconclick()
        this.replay();
      }else if(data.code == "107"){
        this.imglist = this.jsonArry(data)//数据整理
        setTimeout(()=>{
          that.isShowimg = true
        },200)
      }else if(data.code =="400"){
        this.baseUiService.showToast('关闭此次视频公证','customblue','top');
        this.router.navigate(['/tabs/tab2']);
        this.wsCoket.closeWebSocket();
        this.commService.exitRoom();
      }

    })
  }



  //底部弹出
  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: '上传材料',
      buttons: [{
        text: '相册上传',
        icon: 'image-outline',
        handler: () => {
          this.commService.picture(400, 40).subscribe(res => {
            this.getPirture(res)
          })
        }
      }, {
        text: '关闭',
        icon: 'close',
        role: 'cancel',
        handler: () => {
        }
      }]
    });
    await actionSheet.present();
  }


  getPirture(info: any) {
    this.upphotoService.Uploading(info).then(res1 => {
      console.log("同步数据")
      this.materialContent = [...this.materialContent, ...res1]
      setTimeout(()=>{
        this.cd.detectChanges();
      },200)
      this.wsCoket.sendMessage({
        code: '010',
        info: [{
          annexFileList: res1[0]['unitGuid'],
          imgPathList: res1[0]['filePath']
        }],
        userId:this.roomId 
      })
    })
  }

  tabClick(index) {

    switch (index) {
      case "0":
        this.tabIndex = '0';
        break;
      case "1":
        this.tabIndex = '1';
        break;
      case "2":
        this.tabIndex = '2';
        break;
      case "3":
        this.tabIndex = '3';
        break;
      case "4":
        this.tabIndex = '4';
        break;
    }
  }
  //关闭萝卜图
  iconclick() {
    this.imglist = []
    this.isShowimg = false
  }

  /*****
   * 签字
   * **/
  async presentPopover() {
    let dom=document.getElementById("canvas")
    if(!!dom){
        return false
    }
    const modal = await this.modalController.create({
      component: PopoverComponent,
    });
    await modal.present();
    //监听销毁的事件，此时data存的是模态窗口页面销毁时候的值
    const { data } = await modal.onDidDismiss();
    this.signatureImg = data.result.msg
    if (data.result.info) {
      this.upphotoService.Uploading(this.signatureImg, 'must').then(res => {
        if (this.tabIndex == "4") {
          this.wsCoket.sendMessage(this.sendPCmessage(res[0]['filePath'], '205'))//缴费通知
        } else {
          this.wsCoket.sendMessage(this.sendPCmessage(res[0]['filePath'], '020'))
        }

      })

    }
  }

  //向PC端发送消息 this.LoginInfoService.getlocal('orderInfo').roomId ||
  sendPCmessage(message: any, code: any) {
    let info = {
      code: code,
      info: message,
      userId:this.roomId
    }
    return info
  }


  /**
   * **支付宝 付款接口
   * 
   * 
   * @memberOf doSign
  * */
 doSign(){
    let param={
      outTradeNo:this.LoginInfoService.getlocal('orderInfo').orderNo 
    }
    this.HttpService.doSign(param).then(res=>{  
      if(res['code']=="200"){
        this.commService.aliPay(res['item']).subscribe(res=>{
          if(res.trim() =="5001"){
              this.baseUiService.showToast('支付失败','customblue','top');
              this.wsCoket.sendMessage(this.sendPCmessage("","3333"));
              this.doVideologSetState("91");
            }else{
              this.baseUiService.showToast('支付成功','customblue','top');
              this.wsCoket.sendMessage(this.sendPCmessage("","301"));
              this.doVideologSetState("65");
            }
        })
      }
    })
  }


  doVideologSetState(code){
    console.log("doVideologSetState",code);
    let param={
        unitGuid:this.LoginInfoService.getlocal('orderInfo').unitGuid ,
        notaryState: code
    }
    this.HttpService.doVideologSetState(param).then(res=>{  
      if(res['code']=="200"){
        
      }
    })
  }
  //支付
  async replay() {
    const actionSheet = await this.actionSheetController.create({
      header: '支付',
      cssClass:"relay",
      buttons: [{
        text: '支付宝支付',
        role: 'share',
        icon: 'iconfont icon-zhifubao1',
        handler: () => {
          this.doSign();
        }
      }, {
        text: '微信支付',
        role: 'share',
        icon: 'iconfont icon-weixinzhifu1',
        handler: () => {
          this.doSign();
        }
      }, {
        text: '关闭',
        icon: 'close',
        role: 'cancel',
        handler: () => {
        }
      }]
    });
    await actionSheet.present();
  }


}
